package com.ruoyi.user.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.user.service.IAmapService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class AmapServiceImpl implements IAmapService {
    @Value("${amap.key}")
    private String key;

    @Value("${amap.direction.driving-url}")
    private String drivingUrl;

    @Override
    public Object drivingDirection(String origin, String destination, String strategy) {
        String s = strategy == null || strategy.isEmpty() ? "0" : strategy;
        String params = "origin=" + origin + "&destination=" + destination + "&strategy=" + s + "&extensions=all&key=" + key;
        String resp = HttpUtils.sendGet(drivingUrl, params);
        return JSON.parse(resp);
    }

    @Override
    public java.util.Map<String, Object> drivingPolylineData(String origin, String destination, String strategy) {
        String s = strategy == null || strategy.isEmpty() ? "0" : strategy;
        String params = "origin=" + origin + "&destination=" + destination + "&strategy=" + s + "&extensions=all&key=" + key;
        String resp = HttpUtils.sendGet(drivingUrl, params);
        JSONObject obj = JSON.parseObject(resp);
        java.util.Map<String, Object> result = new java.util.HashMap<>();
        JSONObject route = obj.getJSONObject("route");
        if (route == null) return result;
        JSONArray paths = route.getJSONArray("paths");
        if (paths == null || paths.isEmpty()) return result;
        JSONObject path0 = paths.getJSONObject(0);
        result.put("distance", path0.getString("distance"));
        result.put("duration", path0.getString("duration"));
        JSONArray steps = path0.getJSONArray("steps");
        java.util.List<String> points = new java.util.ArrayList<>();
        if (steps != null) {
            for (int i = 0; i < steps.size(); i++) {
                JSONObject step = steps.getJSONObject(i);
                String polyline = step.getString("polyline");
                if (polyline != null && !polyline.isEmpty()) {
                    String[] ps = polyline.split(";");
                    for (String p : ps) {
                        if (!p.isEmpty()) points.add(p);
                    }
                }
            }
        }
        result.put("points", points);
        return result;
    }
}
